package com.zifan.yygh.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zifan.common.result.ResultCodeEnum;
import com.zifan.yygh.dao.DictMapper;
import com.zifan.yygh.exception.YyghException;
import com.zifan.yygh.listener.DictListener;
import com.zifan.yygh.model.cmn.Dict;
import com.zifan.yygh.service.DictService;
import com.zifan.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Zifan
 * @date 2021年09月25日11:46
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 根据id获取该id下所有的子节点
     * 这样不需要一次查出来全部的，前端实现点什么查什么
     */
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator") //开启缓存
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        //where parentId = id。寻找该id下的所有子节点
        wrapper.lambda().eq(Dict::getParentId, id);
        List<Dict> list = this.list(wrapper);
        //elementUI需要一个hasChildren字段。数据库中没有，需要手动设置
        list.forEach(dict -> {
            dict.setHasChildren(getHasChildren(dict.getId()));
        });
        return list;
    }

    /**
     * 导出表格数据
     */
    @Override
    public void exportData(HttpServletResponse response) {
        //设置下载相关头信息
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //获取数据
            List<Dict> list = this.list();
            //封装传输VO
            List<DictEeVo> dictEeVos = list.stream().map(dict -> {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictEeVo);
                return dictEeVo;
            }).collect(Collectors.toList());
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字段").doWrite(dictEeVos);
        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException("下载出错", 2001);
        }

    }

    /**
     * 导入表格数据
     * allEntries = true: 方法调用后清空所有缓存
     */
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(this.baseMapper))
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new YyghException("导入失败！", 20001);
        }
    }

    /**
     * 获取dickName
     */
    @Override
    public String getName(String dictCode, String value) {
        /**
         * 这里逻辑需要说明一下，实际来发中根本不会出现这种逆天的代码
         * 数据库中的value字段不能保证唯一，所以需要上送dictCode字段来确认到底是哪条数据
         */
        if (StrUtil.isEmpty(dictCode)) {
            //直接根据value查询
            QueryWrapper<Dict> wrapperOne = new QueryWrapper<>();
            wrapperOne.lambda().eq(Dict::getValue, value).select(Dict::getName);
            Dict resDict = this.getOne(wrapperOne);
            return ObjectUtil.isNull(resDict) ? "" : resDict.getName();
        } else {
            //先根据dictCode查询出父数据的ID值
            QueryWrapper<Dict> wrapperTwo = new QueryWrapper<>();
            wrapperTwo.lambda().eq(Dict::getDictCode, dictCode).select(Dict::getId);
            Dict resDict = this.getOne(wrapperTwo);

            if (ObjectUtil.isNull(resDict)) {
                return "";
            }

            //注意这里是父数据的的id的值 ！！！！
            Long parentId = resDict.getId();

            //根据父id和value获取唯一的数据
            QueryWrapper<Dict> wrapperThree = new QueryWrapper<>();
            wrapperThree.lambda()
                    //where id = ''
                    .eq(Dict::getParentId, parentId)
                    //and value = ''
                    .eq(Dict::getValue, value)
                    .select(Dict::getName);
            Dict resDictTwo = this.getOne(wrapperThree);
            return ObjectUtil.isNull(resDictTwo) ? "" : resDictTwo.getName();
        }
    }

    /**
     * 根据dictCode获取下级节点
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapperOne = new QueryWrapper<>();
        wrapperOne.lambda()
                .eq(Dict::getDictCode, dictCode)
                .select(Dict::getId);
        Dict resOne = this.getOne(wrapperOne);
        if (ObjectUtil.isNull(resOne)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Long id = resOne.getId();
        QueryWrapper<Dict> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.lambda()
                .eq(Dict::getParentId, id);
        return this.list(wrapperTwo);
    }

    private Boolean getHasChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Dict::getParentId, id);
        //大于0说明又子节点，等于0就是没有
        return this.count(wrapper) > 0;
    }
}
